package net.fpeg.kotlin.msa.wordbase.service

import net.fpeg.kotlin.msa.wordbase.dao.WordUserRelationTypeDao
import net.fpeg.kotlin.msa.wordbase.entity.WordUserRelationType
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import javax.transaction.Transactional


@Service
class WordUserRelationTypeService {

    @Autowired
    lateinit var wordUserRelationTypeDao: WordUserRelationTypeDao

    @Autowired
    lateinit var wordUserService: WordUserService

    @Autowired
    lateinit var wordUserRelationService: WordUserRelationService

    fun fetch(id: Long) = wordUserRelationTypeDao.findByWordUser_IdOrderByIdAsc(id)
    private fun get(typeId: Long) = wordUserRelationTypeDao.getById(typeId)
    fun getOne(typeId: Long) = get(typeId) ?: throw Exception("不存在的")
    fun add(id: Long, value: String) = wordUserRelationTypeDao.save(WordUserRelationType(null, value, wordUserService.getOne(id)))
    fun edit(id: Long, typeId: Long, newValue: String) = getOne(typeId).apply { value = newValue }.let { wordUserRelationTypeDao.save(it) }
    @Transactional
    fun remove(uid: Long, typeId: Long) {
        wordUserRelationService.find(uid, typeId).map {
            it.apply {
                wordUserRelationType = wordUserService.getOne(uid).defaultRelationType ?: throw Exception("卧槽")
            }
        }
        wordUserRelationTypeDao.deleteById(typeId)
    }
}